<template>
  <div>
    <el-dialog
      title="年级报课"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="700px"
      height="700px"
    >
      <el-form :model="form" ref="form" label-width="100px" :rules="formRules">
        <el-form-item label="标题：" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="学生年级：" prop="grade">
          <nice-select
            v-model="form.grade"
            placeholder="请选择学生年级"
            clearable
            :options="selectEnums"
          ></nice-select>
        </el-form-item>
        <el-form-item label="辅导老师：" prop="teacher">
          <el-select
            v-model="form.teacher"
            filterable
            remote
            reserve-keyword
            placeholder="请输入辅导老师"
            :remote-method="remoteTeacherMethod"
            :loading="loading"
            clearable
            @change="changeTeacher"
          >
            <el-option
              v-for="item in teacherList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选课模式：" prop="mode">
          <nice-select
            v-model="form.mode"
            placeholder="请选择选课模式"
            clearable
            :options="courseModeList"
          ></nice-select>
        </el-form-item>
        <div v-for="(item, index) in form.goods" :key="index" class="good-item">
          <el-row>
            <el-col :span="20">
              <el-form-item
                label="商品名称："
                prop="goodname"
                :prop="'goods.' + index + '.goodname'"
                :rules="[
                  {
                    required: true,
                    message: '请选择商品名称',
                    trigger: 'change'
                  }
                ]"
              >
                <el-select
                  v-model="item.goodname"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入商品名称"
                  :remote-method="remoteGoodsMethod"
                  :loading="goodloading"
                  clearable
                  @change="changeGood($event, index)"
                >
                  <el-option
                    v-for="item in goodList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="2" class="margin-top10 margin-left10">
              <i
                class="el-icon-delete"
                @click="deleteGood(item, index)"
                v-if="index !== 0"
              ></i>
            </el-col>
          </el-row>
          <div v-for="(course, indx) in item.courseList" :key="indx">
            <el-row>
              <el-col :span="20">
                <el-form-item label="课程名称：">
                  <span>{{ course.label }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item
                  label="选择期次："
                  :prop="'goods.' + index + '.courseList.' + indx + '.period'"
                  :rules="{
                    required: true,
                    message: '请选择期次',
                    trigger: 'change'
                  }"
                >
                  <nice-select
                    v-model="course.period"
                    placeholder="请选择期次"
                    clearable
                    :options="course.periodList"
                  ></nice-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div
            class="line"
            v-if="index !== form.goods[form.goods.length - 1]"
          ></div>
        </div>
        <el-row>
          <el-col class="center"
            ><el-button
              type="text"
              icon="el-icon-circle-plus"
              size="small"
              @click="addGood()"
              >添加商品</el-button
            ></el-col
          >
        </el-row>
        <el-form-item label="选择优惠：" prop="favorable">
          <nice-select
            v-model="form.favorable"
            placeholder="请选择优惠"
            clearable
            :options="favoureList"
          ></nice-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryCounselorList,
  queryGoodsListByTerm,
  insertCoursePlanAndDetail,
  editCoursePlanAndDetail,
  queryCoursePlanDetails
} from "@/api/user.js";
export default {
  data() {
    return {
      visible: false,
      id: "",
      teacherList: [],
      termList: [],
      loading: false,
      form: {
        title: "",
        grade: "",
        teacher: "",
        mode: 0,
        goods: [{ goodname: "", courseList: [] }],
        favorable: ""
      },
      goodList: [],
      goodloading: false,
      courseModeList: [
        { label: "不允许学生自主选课", value: 0 },
        { label: "允许学生自主选课", value: 1 }
      ],
      formRules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        grade: [
          { required: true, message: "请选择学生年级", trigger: "change" }
        ],
        teacher: [
          { required: true, message: "请选择辅导老师", trigger: "change" }
        ],
        mode: [{ required: true, message: "请选择选课模式", trigger: "change" }]
      }
    };
  },
  props: {
    selectEnums: {
      type: Array,
      default: function() {
        return [];
      }
    },
    favoureList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    schoolId: ""
  },
  methods: {
    init(id) {
      this.visible = true;
      this.id = id;
      if (id) {
        this.$nextTick(() => {
          this.$refs.form.resetFields();
          this.getDetails();
        });
      } else {
        this.$nextTick(() => {
          this.goodList = [];
          this.termList = [];
          this.teacherList = [];
          this.$refs.form.resetFields();
          this.form.favorable = this.favoureList[1].value;
          this.form.goods = [{ goodname: "", courseList: [] }];
        });
      }
    },
    async getDetails() {
      let res = await queryCoursePlanDetails({ "vo.course_plan_id": this.id });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        this.form.goods = [];
        let detail = res[1].data.data;
        this.form.title = detail.title;
        this.form.grade = detail.grade;
        this.form.mode = detail.choose_course_type;
        this.form.favorable = detail.preferential_type;
        this.teacherList = [{ label: detail.real_name, value: detail.user_id }];
        this.form.teacher = detail.user_id;
        this.goodList = detail.goodList.map(item => {
          item.goods_name = item.goods_name + " " + item.retail_price + "元";
          return {
            label: item.goods_name,
            value: item.id,
            courseList: item.courseList
          };
        });
        detail.goodList.forEach(ele => {
          let courseList = [];
          ele.courseList.forEach(item => {
            let start_date = item.period.start_date
              ? item.period.start_date.substring(0, 10)
              : "";
            let end_date = item.period.end_date
              ? item.period.end_date.substring(0, 10)
              : "";
            let date = start_date ? start_date + "~" + end_date : "";
            let frequency = item.period.frequency
              ? JSON.parse(item.period.frequency)
              : [];
            let week = "周" + this.$filterFrequency(frequency);
            let label =
              "第" + item.period.sort + "期" + " " + date + " " + week;
            courseList.push({
              value: item.course_id,
              label: item.course_name + " " + item.lesson_count + "讲",
              period: item.period.id,
              periodList: [
                {
                  label: label,
                  value: item.period.id,
                  sort: item.period.sort
                }
              ]
            });
          });
          this.form.goods.push({
            goodname: ele.id,
            courseList: courseList
          });
        });
      }
    },
    changeTeacher(val) {
      this.teacherList = [];
    },
    async remoteTeacherMethod(query) {
      if (query !== "") {
        this.loading = true;
        let res = await queryCounselorList({ real_name: query });
        if (res[0]) {
          return;
        }
        this.loading = false;
        if (res[1] && res[1].code === 0) {
          this.teacherList = [];
          if (res[1].counselorList && res[1].counselorList.length) {
            res[1].counselorList.forEach(ele => {
              this.teacherList.push({
                label: ele.real_name,
                value: ele.sys_user_id
              });
            });
          }
        }
      }
    },
    async remoteGoodsMethod(query) {
      if (query !== "") {
        this.goodloading = true;
        let res = await queryGoodsListByTerm({ goods_name: query });
        if (res[0]) {
          return;
        }
        this.goodloading = false;
        if (res[1] && res[1].code === 0) {
          this.goodList = [];
          if (res[1].coursePlanList && res[1].coursePlanList.length) {
            this.goodList = res[1].coursePlanList.map(ele => {
              ele.goods_name = ele.goods_name + " " + ele.retail_price + "元";
              return {
                label: ele.goods_name,
                value: ele.id,
                courseList: ele.courseList
              };
            });
          }
        }
      }
    },
    addGood() {
      this.form.goods.push({ goodname: "", courseList: [] });
    },
    deleteGood(item, index) {
      this.form.goods.splice(index, 1);
    },
    dataFormSubmit() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let goodList = [];
          let list = [];
          this.form.goods.forEach(ele => {
            list.push(ele.goodname);
            ele.courseList.forEach(item => {
              let sort = "";
              item.periodList.forEach(period => {
                if (period.value === item.period) {
                  sort = period.sort;
                }
              });
              goodList.push({
                goods_id: ele.goodname,
                course_id: item.value,
                course_period_id: item.period,
                period_sort: sort
              });
            });
          });
          if (this.form.goods.length > Array.from(new Set(list)).length) {
            this.$message.warning("同一个商品不能选择多次！");
            return false;
          }
          let res = this.id
            ? await editCoursePlanAndDetail({
                "nice_school_course_plan.id": this.id,
                "nice_school_course_plan.user_id": this.form.teacher,
                "nice_school_course_plan.preferential_type": this.form
                  .favorable,
                "nice_school_course_plan.choose_course_type": this.form.mode,
                "nice_school_course_plan.title": this.form.title,
                "nice_school_course_plan.grade": this.form.grade,
                "nice_school_course_plan_detail.array": goodList
              })
            : await insertCoursePlanAndDetail([
                {
                  list: [
                    {
                      title: this.form.title,
                      school_id: this.schoolId,
                      grade: this.form.grade,
                      user_id: this.form.teacher,
                      preferential_type: this.form.favorable,
                      operator: +localStorage.getItem("sys_user_id"),
                      choose_course_type: this.form.mode,
                      courseplan: goodList
                    }
                  ],
                  table_name: "nice_school_course_plan"
                }
              ]);
          if (res[0]) {
          }
          if (res[1] && res[1].code === 0) {
            this.$message.success(
              this.id ? "编辑年级报课成功！" : "新增年级报课成功！"
            );
            this.visible = false;
            this.$emit("refreshDataList");
          }
        }
      });
    },
    changeGood(val, index) {
      this.goodList.forEach(ele => {
        if (val === ele.value) {
          this.courseList = [];
          if (ele.courseList && ele.courseList.length) {
            ele.courseList.forEach(item => {
              let periodList = [];
              if (item.coursePeriodList && item.coursePeriodList.length) {
                item.coursePeriodList.forEach(period => {
                  period.start_date = period.start_date
                    ? period.start_date.substring(0, 10)
                    : "";
                  period.end_date = period.end_date
                    ? period.end_date.substring(0, 10)
                    : "";
                  let date = period.start_date
                    ? period.start_date + "~" + period.end_date
                    : "";
                  let frequency = period.frequency
                    ? JSON.parse(period.frequency)
                    : [];
                  let week = "周" + this.$filterFrequency(frequency);
                  period.label =
                    "第" + period.sort + "期" + " " + date + " " + week;
                  periodList.push({
                    label: period.label,
                    value: period.id,
                    sort: period.sort
                  });
                });
              }
              this.courseList.push({
                value: item.course_id,
                label: item.course_name + " " + item.total_lesson + "讲",
                period: "",
                periodList: periodList
              });
            });
            this.$set(this.form.goods, index, {
              goodname: val,
              courseList: this.courseList
            });
          }
        }
      });
      this.goodList = [];
    }
  }
};
</script>
<style lang="scss" scoped>
.good-item {
  margin-bottom: 20px;
  .line {
    height: 1px;
    background: #dcdfe6;
    margin-left: 10px;
  }
}
</style>
